﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ANZ_AIM_GUI.Utils;
using ANZ_AIM_BLL.Model;
using ANZ_AIM_BLL;
using System.Runtime.InteropServices;
using log4net;

namespace ANZ_AIM_GUI
{
    public partial class frmMain : Form
    {
        //log4net
        private static readonly ILog logger = LogManager.GetLogger(typeof(frmMain));

        public static int sessiontimeout = 0;

        [DllImport("user32.dll")]
        public static extern Boolean GetLastInputInfo(ref tagLASTINPUTINFO plii);

        public struct tagLASTINPUTINFO
        {
            public uint cbSize;
            public Int32 dwTime;
        }

        protected AppParam appParam = AppParam.Instance;

        public frmMain()
        {
            try
            {
                InitializeComponent();
                tmSession.Interval = 1000;
                tmSession.Enabled = true;
                tmSession.Start();

                sessiontimeout = GetParamMaxSession();

                // Check path of DB log
                LogBLL db = new LogBLL();
                db.CheckConnection();

                checkNofityDIS();
            }
            catch (Exception ex) { throw ex; }
        }

        private void mnuLogin_Click(object sender, EventArgs e)
        {
            try
            {
                loginAction();
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.InnerException == null ? ex.Message : ex.InnerException.Message, Constant.SYS_ERROR, MessageBoxButtons.OK);
                logger.Error(ex.Message + " - " + ex.StackTrace);
            }
        }

        private void loginAction()
        {
            try
            {
                //log.Info("test info");
                frmLogin frmLogin = new frmLogin(this);
                DialogResult result = frmLogin.ShowDialog(this);
                if (result == DialogResult.Yes)
                {
                    mnuPermission(appParam.Role);
                    this.mnuLogin.Visible = false;
                    this.mnuChangePwd.Visible = true;
                    this.mnuLogout.Visible = true;
                    if (frmLogin.NeedToChangePwd)
                    {
                        frmChangePassword frmChangePwd = new frmChangePassword();
                        DialogResult retChange = frmChangePwd.ShowDialog();
                        if (retChange != DialogResult.OK)
                            return;
                    }
                }
            }
            catch (Exception ex) { throw ex; }
        }

        private void mnuPermission(string[] userRole)
        {
            try
            {
                //logoutAction(true);
                this.mnuSystemInformation.Visible = userRole.Contains(User.ROLE_ADMIN);
                this.mnuAdmin.Visible = userRole.Contains(User.ROLE_ADMIN);
                this.mnuCandidate.Visible = userRole.Contains(User.ROLE_APPROVER) || userRole.Contains(User.ROLE_EXECUTER)
                                                          || userRole.Contains(User.ROLE_VERIFIER) || userRole.Contains(User.ROLE_VIEWER);
                this.mnuSale.Visible = userRole.Contains(User.ROLE_APPROVER) || userRole.Contains(User.ROLE_EXECUTER)
                                                          || userRole.Contains(User.ROLE_VERIFIER) || userRole.Contains(User.ROLE_VIEWER);
                this.mnuReport.Visible = userRole.Contains(User.ROLE_APPROVER) || userRole.Contains(User.ROLE_EXECUTER)
                                                          || userRole.Contains(User.ROLE_VERIFIER) || userRole.Contains(User.ROLE_VIEWER);
                this.mnuLog.Visible = userRole.Contains(User.ROLE_ADMIN);

                this.mnuUploadCandidate.Visible = userRole.Contains(User.ROLE_EXECUTER) || userRole.Contains(User.ROLE_VIEWER);
                this.mnuUploadCandidate.Text = (userRole.Contains(User.ROLE_VIEWER) && !userRole.Contains(User.ROLE_EXECUTER)) ? "View" : "Upload";
                this.mnuVerifyCandidate.Visible = userRole.Contains(User.ROLE_VERIFIER);
                this.menuApproveCandidate.Visible = userRole.Contains(User.ROLE_APPROVER);
                this.mnuEditSaleInfo.Visible = userRole.Contains(User.ROLE_EXECUTER) || userRole.Contains(User.ROLE_VIEWER);
                this.mnuEditSaleInfo.Text = (userRole.Contains(User.ROLE_VIEWER) && !userRole.Contains(User.ROLE_EXECUTER)) ? "View Sale Info" : "Edit Sale Info";
                this.mnuUploadSaleInfo.Visible = userRole.Contains(User.ROLE_EXECUTER);
                this.mnuVerifySaleInfo.Visible = userRole.Contains(User.ROLE_VERIFIER);
                this.mnuApproveSaleInfo.Visible = userRole.Contains(User.ROLE_APPROVER);
            }
            catch (Exception ex) { throw ex; }
        }

        private void mnuChangePwd_Click(object sender, EventArgs e)
        {
            frmChangePassword fmChangePwd = new frmChangePassword();
            fmChangePwd.ShowDialog(this);
        }

        private void mnuUserMgm_Click(object sender, EventArgs e)
        {
            frmAdmin fmAdmin = new frmAdmin();
            fmAdmin.ShowDialog();
        }

        private void mnuExit_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void mnuLogout_Click(object sender, EventArgs e)
        {
            MenuLogoutClicked();

            this.mnuLogin.Visible = true;
            this.mnuChangePwd.Visible = false;
            this.mnuLogout.Visible = false;
            
            logoutAction();
            loginAction();
        }

        private void logoutAction(Boolean isLogout = true)
        {
            this.mnuAdmin.Visible = !isLogout;
            this.mnuCandidate.Visible = !isLogout;
            this.mnuSale.Visible = !isLogout;
            this.mnuReport.Visible = !isLogout;            
            this.mnuLog.Visible = !isLogout;

            this.mnuUploadCandidate.Visible = !isLogout;
            this.mnuVerifyCandidate.Visible = !isLogout;
            this.menuApproveCandidate.Visible = !isLogout;
            this.mnuEditSaleInfo.Visible = !isLogout;
            this.mnuUploadSaleInfo.Visible = !isLogout;
            this.mnuVerifySaleInfo.Visible = !isLogout;
            this.mnuApproveSaleInfo.Visible = !isLogout;
        }

        private void MenuLogoutClicked()
        {
            try
            {
                appParam.LoggedIn = false;
                appParam.UserId = null;
                appParam.UserName = null;
                appParam.Role = null;
                appParam.PathFile = null;
            }
            catch (Exception ex) { throw ex; }
        }

        private void tmSession_Tick(object sender, EventArgs e)
        {
            tagLASTINPUTINFO LastInput = new tagLASTINPUTINFO();
            Int32 IdleTime;
            LastInput.cbSize = (uint)Marshal.SizeOf(LastInput);
            LastInput.dwTime = 0;
            if (GetLastInputInfo(ref LastInput))
            {
                IdleTime = System.Environment.TickCount - LastInput.dwTime;
                if (IdleTime > sessiontimeout)
                {
                    Application.Exit();
                }
            }
        }

        private static int GetParamMaxSession()
        {
            try
            {
                int maxDefault = 30 * 60 * 1000; // Default Max Wrong Password
                ConfigurationBLL configBll = new ConfigurationBLL();
                Configuration config = configBll.GetByKey(Configuration.SESSION_TIMEOUT_MAX);
                int newMax = maxDefault;
                if (config != null && !string.IsNullOrEmpty(config.ConfigValue))
                {
                    if (int.TryParse(config.ConfigValue, out newMax))
                    {

                    }
                }

                return newMax;
            }
            catch (Exception ex) { throw ex; }
        }

        private void mnuEditSaleInfo_Click(object sender, EventArgs e)
        {
            try
            {
                frmSalesMgmt frmSaleChange = new frmSalesMgmt();
                frmSaleChange.ShowDialog(this);
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.InnerException == null ? ex.Message : ex.InnerException.Message, Constant.SYS_ERROR, MessageBoxButtons.OK);
                logger.Error(ex.Message + " - " + ex.StackTrace);
            }
        }

        private void mnuUploadSaleInfo_Click(object sender, EventArgs e)
        {
            try
            {
                frmSaleChangeUpload frmSaleChangeUpload = new frmSaleChangeUpload();
                frmSaleChangeUpload.ShowDialog(this);
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.InnerException == null ? ex.Message : ex.InnerException.Message, Constant.SYS_ERROR, MessageBoxButtons.OK);
                logger.Error(ex.Message + " - " + ex.StackTrace);
            }
        }

        private void mnuVerifySaleInfo_Click(object sender, EventArgs e)
        {
            try
            {
                frmSaleChangeMgmt frmSaleChangeMgmt = new frmSaleChangeMgmt(false);
                frmSaleChangeMgmt.ShowDialog(this);
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.InnerException == null ? ex.Message : ex.InnerException.Message, Constant.SYS_ERROR, MessageBoxButtons.OK);
                logger.Error(ex.Message + " - " + ex.StackTrace);
            }
        }

        private void mnuApproveSaleInfo_Click(object sender, EventArgs e)
        {
            try
            {
                frmSaleChangeMgmt frmSaleChangeMgmt = new frmSaleChangeMgmt(true);
                frmSaleChangeMgmt.ShowDialog(this);
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.InnerException == null ? ex.Message : ex.InnerException.Message, Constant.SYS_ERROR, MessageBoxButtons.OK);
                logger.Error(ex.Message + " - " + ex.StackTrace);
            }
        }

       

        private void mnuUploadCandidate_Click(object sender, EventArgs e)
        {
            try
            {
                frmCandidateUpload frmCandidateUpload = new frmCandidateUpload();
                frmCandidateUpload.ShowDialog(this);
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.InnerException == null ? ex.Message : ex.InnerException.Message, Constant.SYS_ERROR, MessageBoxButtons.OK);
                logger.Error(ex.Message + " - " + ex.StackTrace);
            }
        }

        private void mnuVerifyCandidate_Click(object sender, EventArgs e)
        {
            try
            {
                frmCandidateApproved frmCandidateVerify = new frmCandidateApproved(false);
                frmCandidateVerify.ShowDialog(this);
            }
            catch(Exception ex)
            {
                MessageBox.Show(this, ex.InnerException == null ? ex.Message : ex.InnerException.Message, Constant.SYS_ERROR, MessageBoxButtons.OK);
                logger.Error(ex.Message + " - " + ex.StackTrace);
            }
        }

        private void menuApproveCandidate_Click(object sender, EventArgs e)
        {
            try
            {
                frmCandidateApproved frmCandidateVerify = new frmCandidateApproved(true);
                frmCandidateVerify.ShowDialog(this);
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.InnerException == null ? ex.Message : ex.InnerException.Message, Constant.SYS_ERROR, MessageBoxButtons.OK);
                logger.Error(ex.Message + " - " + ex.StackTrace);
            }
        }

        private void reportToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                frmReport frmReport = new frmReport();
                frmReport.ShowDialog(this);
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.InnerException == null ? ex.Message : ex.InnerException.Message, Constant.SYS_ERROR, MessageBoxButtons.OK);
                logger.Error(ex.Message + " - " + ex.StackTrace);
            }
        }

        private void toolStripMenuItem1_Click(object sender, EventArgs e)
        {
            try
            {
                frmReport frmReport = new frmReport(2);
                frmReport.DISUpdateStatus = new frmReport.SetUpdate(UpdateStatusDisciplinary);
                frmReport.Show();
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.InnerException == null ? ex.Message : ex.InnerException.Message, Constant.SYS_ERROR, MessageBoxButtons.OK);
                logger.Error(ex.Message + " - " + ex.StackTrace);
            }
        }

        private void checkNofityDIS()
        {
            try
            {
                SaleDISBLL saleDISBll = new SaleDISBLL();
                int sumNotify = saleDISBll.NotifyDIS();
                UpdateStatusDisciplinary(sumNotify.ToString());
            }
            catch (Exception ex) { throw ex; }
        }
        private void UpdateStatusDisciplinary(string text)
        {
            toolStripMenuItem1.Text = "Disciplinary (" + text + ")";
        }

        private void frmMain_Load(object sender, EventArgs e)
        {
            loginAction();
        }

        private void logToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                frmShowLog frmShowLog = new frmShowLog();
                frmShowLog.ShowDialog(this);
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.InnerException == null ? ex.Message : ex.InnerException.Message, Constant.SYS_ERROR, MessageBoxButtons.OK);
                logger.Error(ex.Message + " - " + ex.StackTrace);
            }
        }

        private void mnuSystemInformation_Click(object sender, EventArgs e)
        {
            frmSystemInformation frm = new frmSystemInformation();
            frm.ShowDialog();
        }

        private void frmMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (e.CloseReason == CloseReason.UserClosing)
            {
                DialogResult result = MessageBox.Show(Constant.SYS_MSG_EXIT_APP, "Confirmation", MessageBoxButtons.YesNo, MessageBoxIcon.Question,
                        MessageBoxDefaultButton.Button2);
                if (result == DialogResult.No)
                {
                    e.Cancel = true;
                }
            }
        }
    }
}
